package com.ks.demo.listener;

import com.ks.demo.config.CommonKey;
import com.rabbitmq.client.Channel;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.messaging.handler.annotation.Header;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * @Author：kangsen
 * @Date：2022/9/26/0026 23:39
 * @Versiion：1.0
 * @Desc:
 *
 * 有多个消费者时 会轮询消费且不会重复消费
 *
 *
 */
@Component
@Slf4j
public class DirectListener {

    @SneakyThrows
    @RabbitListener(queues = CommonKey.DIRECT_QUEUE_NAME,concurrency = "10")
    @RabbitHandler
    public void receiver(Map msg, Message message, Channel channel, @Header(AmqpHeaders.DELIVERY_TAG) long deliveryTag){
        /*try {
            log.info("receive : {}",msg);
            //确认消息消费成功
            if("ming".equalsIgnoreCase(msg.get("msg").toString())){
                throw new Exception("手动抛异常");
            }
            channel.basicAck(deliveryTag, true);
        } catch (Exception e) {
            log.error("接收消息异常：{}",e);
            //异常 将消息返回给Queue里，第三个参数requeue可以直接看出来 是否回到queue中
            channel.basicNack(deliveryTag,true,true);
        }*/

        log.info("receive : {}",msg);
        //确认消息消费成功
        if("ming".equalsIgnoreCase(msg.get("msg").toString())){
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), true);
             //throw new Exception("手动抛异常");
        }else{
            channel.basicAck(deliveryTag,true);
        }
    }
}
